<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="updateVisible"
    title="导出自动化测试脚本"
    width="600px"
    :before-close="handleClose"
    destroy-on-close
  >
    <div class="space-y-4">
      <!-- 脚本名称 -->
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-2">脚本名称</label>
        <el-input
          v-model="scriptName"
          placeholder="请输入脚本名称"
          class="w-full"
        />
      </div>

      <!-- 导出格式 -->
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-2">导出格式</label>
        <div class="grid grid-cols-2 gap-3">
          <div 
            class="border rounded-md p-3 cursor-pointer transition-all"
            :class="selectedFormat === 'playwright' ? 'border-primary bg-blue-50' : 'border-gray-200 hover:border-gray-300'"
            @click="selectedFormat = 'playwright'"
          >
            <div class="flex items-center">
              <div 
                class="w-4 h-4 rounded-full border-2 flex items-center justify-center mr-2"
                :class="selectedFormat === 'playwright' ? 'border-primary bg-primary' : 'border-gray-300'"
              >
                <div v-if="selectedFormat === 'playwright'" class="w-2 h-2 bg-white rounded-full"></div>
              </div>
              <span class="text-sm font-medium">Playwright</span>
            </div>
            <p class="text-xs text-gray-500 mt-1 ml-6">JavaScript/TypeScript 格式的 Playwright 测试脚本</p>
          </div>
          
          <div 
            class="border rounded-md p-3 cursor-pointer transition-all"
            :class="selectedFormat === 'jsonl' ? 'border-primary bg-blue-50' : 'border-gray-200 hover:border-gray-300'"
            @click="selectedFormat = 'jsonl'"
          >
            <div class="flex items-center">
              <div 
                class="w-4 h-4 rounded-full border-2 flex items-center justify-center mr-2"
                :class="selectedFormat === 'jsonl' ? 'border-primary bg-primary' : 'border-gray-300'"
              >
                <div v-if="selectedFormat === 'jsonl'" class="w-2 h-2 bg-white rounded-full"></div>
              </div>
              <span class="text-sm font-medium">JSONL</span>
            </div>
            <p class="text-xs text-gray-500 mt-1 ml-6">每行一个 JSON 对象的格式</p>
          </div>
        </div>
      </div>

      <!-- TypeScript选项 (仅在Playwright格式下显示) -->
      <div v-if="selectedFormat === 'playwright'">
        <label class="block text-sm font-medium text-gray-700 mb-2">语言类型</label>
        <div class="grid grid-cols-2 gap-3">
          <div 
            class="border rounded-md p-3 cursor-pointer transition-all"
            :class="!isTypeScript ? 'border-primary bg-blue-50' : 'border-gray-200 hover:border-gray-300'"
            @click="isTypeScript = false"
          >
            <div class="flex items-center">
              <div 
                class="w-4 h-4 rounded-full border-2 flex items-center justify-center mr-2"
                :class="!isTypeScript ? 'border-primary bg-primary' : 'border-gray-300'"
              >
                <div v-if="!isTypeScript" class="w-2 h-2 bg-white rounded-full"></div>
              </div>
              <span class="text-sm font-medium">JavaScript (.js)</span>
            </div>
          </div>
          
          <div 
            class="border rounded-md p-3 cursor-pointer transition-all"
            :class="isTypeScript ? 'border-primary bg-blue-50' : 'border-gray-200 hover:border-gray-300'"
            @click="isTypeScript = true"
          >
            <div class="flex items-center">
              <div 
                class="w-4 h-4 rounded-full border-2 flex items-center justify-center mr-2"
                :class="isTypeScript ? 'border-primary bg-primary' : 'border-gray-300'"
              >
                <div v-if="isTypeScript" class="w-2 h-2 bg-white rounded-full"></div>
              </div>
              <span class="text-sm font-medium">TypeScript (.ts)</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 导出选项 -->
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-2">导出选项</label>
        <div class="space-y-2">
          <el-checkbox v-model="exportOptions.includeComments">
            包含注释
          </el-checkbox>
          <el-checkbox v-model="exportOptions.includeScreenshots">
            包含截图步骤
          </el-checkbox>
          <el-checkbox v-model="exportOptions.prettyFormat">
            美化代码格式
          </el-checkbox>
          <el-checkbox v-model="exportOptions.includeMetadata" v-if="selectedFormat === 'jsonl'">
            包含元数据信息
          </el-checkbox>
        </div>
      </div>

      <!-- 步骤选择 -->
      <div>
        <div class="flex items-center justify-between mb-2">
          <label class="block text-sm font-medium text-gray-700">选择要导出的步骤</label>
          <div class="space-x-2">
            <el-button size="small" text @click="selectAllSteps">全选</el-button>
            <el-button size="small" text @click="selectNoneSteps">全不选</el-button>
          </div>
        </div>
        <div class="max-h-40 overflow-y-auto border border-gray-200 rounded-md p-2">
          <div v-if="availableSteps.length === 0" class="text-center text-gray-500 py-4">
            <el-icon class="text-2xl mb-2"><i-ep-document /></el-icon>
            <p class="text-sm">暂无可导出的步骤</p>
            <p class="text-xs text-gray-400">请先录制或导入一些步骤</p>
          </div>
          <div v-else class="space-y-1">
            <div
              v-for="step in availableSteps"
              :key="step.stepNumber"
              class="flex items-center p-2 hover:bg-gray-50 rounded"
            >
              <el-checkbox 
                v-model="selectedSteps"
                :label="step.stepNumber"
                class="mr-3"
              />
              <el-icon class="mr-2 text-gray-600">
                <component :is="getStepIcon(step.type)" />
              </el-icon>
              <div class="flex-1">
                <div class="text-sm">{{ step.description || step.name }}</div>
                <div class="text-xs text-gray-500">{{ step.selector || step.url || step.details }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 预览区域 -->
      <div>
        <div class="flex items-center justify-between mb-2">
          <span class="text-sm font-medium text-gray-700">预览</span>
          <el-button size="small" text @click="copyPreviewCode">
            <el-icon class="mr-1"><i-ep-copy-document /></el-icon>
            复制代码
          </el-button>
        </div>
        <div class="border border-gray-200 rounded-md p-4 bg-gray-50">
          <pre class="text-xs font-mono bg-gray-100 p-3 rounded-md max-h-32 overflow-auto whitespace-pre-wrap">{{ previewCode || '请选择步骤以生成预览' }}</pre>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="flex justify-between">
        <div class="text-sm text-gray-500">
          已选择 {{ selectedSteps.length }} 个步骤
        </div>
        <div>
          <el-button @click="handleClose">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmExport"
            :disabled="selectedSteps.length === 0"
          >
            导出脚本
          </el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useScriptStore } from '../stores/script'
import { ElMessage } from 'element-plus'
import { 
  Document as iEpDocument,
  CopyDocument as iEpCopyDocument,
  Link as iEpLink,
  Edit as iEpEdit,
  Mouse as iEpMouse,
  View as iEpView,
  Clock as iEpClock,
  Camera as iEpCamera
} from '@element-plus/icons-vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:visible', 'confirm'])

const scriptStore = useScriptStore()

// 响应式数据
const scriptName = ref('login_test')
const selectedFormat = ref('playwright')
const isTypeScript = ref(false)
const selectedSteps = ref([])
const previewCode = ref('')

const exportOptions = ref({
  includeComments: true,
  includeScreenshots: false,
  prettyFormat: true,
  includeMetadata: false
})

// 计算属性
const updateVisible = (value) => emit('update:visible', value)

const availableSteps = computed(() => {
  return scriptStore.steps || []
})

// 监听选择变化，自动生成预览
watch([selectedSteps, selectedFormat, isTypeScript, exportOptions], () => {
  generatePreview()
}, { deep: true })

// 监听对话框打开，初始化数据
watch(() => props.visible, (newVal) => {
  if (newVal) {
    initializeData()
  }
})

// 方法
const handleClose = () => {
  emit('update:visible', false)
  resetForm()
}

const resetForm = () => {
  scriptName.value = 'login_test'
  selectedFormat.value = 'playwright'
  isTypeScript.value = false
  selectedSteps.value = []
  previewCode.value = ''
  exportOptions.value = {
    includeComments: true,
    includeScreenshots: false,
    prettyFormat: true,
    includeMetadata: false
  }
}

const initializeData = () => {
  // 默认选择所有步骤
  selectedSteps.value = availableSteps.value.map(step => step.stepNumber)
  generatePreview()
}

const selectAllSteps = () => {
  selectedSteps.value = availableSteps.value.map(step => step.stepNumber)
}

const selectNoneSteps = () => {
  selectedSteps.value = []
}

const generatePreview = async () => {
  if (selectedSteps.value.length === 0) {
    previewCode.value = ''
    return
  }

  try {
    // 使用脚本管理器进行导出
    const { scriptManager } = await import('../services/scriptManager.js')
    
    // 获取选中的步骤
    const stepsToExport = availableSteps.value.filter(step => 
      selectedSteps.value.includes(step.stepNumber)
    )
    
    const result = scriptManager.exportScript({
      scriptName: scriptName.value,
      format: selectedFormat.value,
      isTypeScript: isTypeScript.value,
      steps: stepsToExport,
      ...exportOptions.value
    })
    
    if (result.success) {
      previewCode.value = result.content
    } else {
      previewCode.value = '// 生成预览失败: ' + result.message
    }
  } catch (error) {
    console.error('生成预览失败:', error)
    previewCode.value = '// 生成预览失败: ' + error.message
  }
}

const copyPreviewCode = async () => {
  if (!previewCode.value) {
    ElMessage.warning('没有可复制的代码')
    return
  }

  try {
    await navigator.clipboard.writeText(previewCode.value)
    ElMessage.success('代码已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败，请手动复制')
  }
}

const confirmExport = async () => {
  if (selectedSteps.value.length === 0) {
    ElMessage.warning('请选择要导出的步骤')
    return
  }

  try {
    // 使用脚本管理器进行导出
    const { scriptManager } = await import('../services/scriptManager.js')
    
    const stepsToExport = availableSteps.value.filter(step => 
      selectedSteps.value.includes(step.stepNumber)
    )
    
    const result = scriptManager.exportScript({
      scriptName: scriptName.value,
      format: selectedFormat.value,
      isTypeScript: isTypeScript.value,
      steps: stepsToExport,
      ...exportOptions.value
    })
    
    if (result.success) {
      // 创建下载链接
      const fileExtension = selectedFormat.value === 'jsonl' ? '.jsonl' : 
                           (isTypeScript.value ? '.ts' : '.js')
      const mimeType = selectedFormat.value === 'jsonl' ? 'application/jsonl' :
                      (isTypeScript.value ? 'text/typescript' : 'text/javascript')
      
      const blob = new Blob([result.content], { type: mimeType })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `${scriptName.value}${fileExtension}`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
      
      ElMessage.success('脚本导出成功！')
      
      // 触发确认事件
      emit('confirm', {
        scriptName: scriptName.value,
        format: selectedFormat.value,
        isTypeScript: isTypeScript.value,
        selectedSteps: selectedSteps.value,
        exportOptions: exportOptions.value,
        content: result.content,
        filename: result.filename
      })
      
      handleClose()
    } else {
      ElMessage.error('导出失败: ' + result.message)
    }
  } catch (error) {
    console.error('导出脚本失败:', error)
    ElMessage.error('导出脚本失败: ' + error.message)
  }
}

// 获取步骤图标
const getStepIcon = (type) => {
  const iconMap = {
    'navigation': iEpLink,
    'input': iEpEdit,
    'click': iEpMouse,
    'assertion': iEpView,
    'wait': iEpClock,
    'screenshot': iEpCamera
  }
  return iconMap[type] || iEpDocument
}
</script>

<style scoped>
.whitespace-pre-wrap {
  white-space: pre-wrap;
  word-break: break-word;
}
</style>
